import axios from "axios";
import { ElMessage } from "element-plus";
import router from "@/router";
import qs from "qs";

const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 25000,
  withCredentials: true,
});

// 拦截请求
service.interceptors.request.use(
  (config) => {
    // 对get请求进行参数序列化
    if (config.method === "get" && config.params) {
      const serializedParams = qs.stringify(config.params);
      // 如果URL中已经有查询参数，则添加&；否则，添加?
      if (config.url.includes("?")) {
        config.url += `&${serializedParams}`;
      } else {
        config.url += `?${serializedParams}`;
      }
      // 如果你不想在请求中发送config.params（因为已经手动添加到URL），可以删除它
      delete config.params;
    }
    // const { authorization } = useApp()
    // if (authorization) {
    //   config.headers.Authorization = `${authorization.token}`
    // }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 拦截响应
service.interceptors.response.use((response) => {
  if (response.data.code != 1000001) {
    ElMessage({
      message: response.data.message,
      type: "warning",
    });
  }
  return response.data;
});

export default service;
